package com.topit.show.core.util;

import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import com.bike.util.PageData;

public class XmlUtil {
		public static String getXmlParams(Map<String, String> params) {
			StringBuilder xmlStr = new StringBuilder();
			xmlStr.append("<xml>");
			for (String key : params.keySet()) {
				xmlStr.append("<").append(key).append(">");
				xmlStr.append(params.get(key));
				xmlStr.append("</").append(key).append(">");
			}
			xmlStr.append("</xml>");
			return xmlStr.toString();
	}
		
	/**
	 * 解析xml
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public static Map<String, String> parseXml(HttpServletRequest request) throws Exception {
		// 讲解析结果存放刀到map中
		Map<String, String> msgMap = new HashMap<String, String>();
		SAXReader reader = new SAXReader();
		InputStream inputStream = request.getInputStream();
		Document document = reader.read(inputStream);
		Element root = document.getRootElement();
		List<Element> elementList = root.elements();
		for (Element e : elementList) {
			msgMap.put(e.getName(), e.getText());
		}
		inputStream.close();
		inputStream = null;
		return msgMap;
	}
	/**
	 * 解析xml
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public static PageData parseXmlToPageData(HttpServletRequest request) throws Exception {
		// 讲解析结果存放刀到map中
		PageData msgMap = new PageData();
		SAXReader reader = new SAXReader();
		InputStream inputStream = request.getInputStream();
		Document document = reader.read(inputStream);
		Element root = document.getRootElement();
		List<Element> elementList = root.elements();
		for (Element e : elementList) {
			msgMap.put(e.getName(), e.getText());
		}
		inputStream.close();
		inputStream = null;
		return msgMap;
	}

}
